package com.isoft.c2team3service2.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isoft.c2team3service2.bean.PageResult;
import com.isoft.c2team3service2.entity.UserMessage;
import com.isoft.c2team3service2.entity.UserDTO;
import com.isoft.c2team3service2.entity.UserMessageStatus;
import com.isoft.c2team3service2.entity.UserMessageVO;
import com.isoft.c2team3service2.mapper.UserMessageMapper;
import com.isoft.c2team3service2.mapper.UserMessageStatusMapper;
import com.isoft.c2team3service2.mapper.UserFollowMapper;
import com.isoft.c2team3service2.service.UserMessageService;
import com.isoft.c2team3service2.util.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserMessageServiceImpl extends ServiceImpl<UserMessageMapper, UserMessage> implements UserMessageService {

    @Autowired
    private UserMessageMapper userMessageMapper;

    @Autowired
    private UserMessageStatusMapper messageStatusMapper;

    @Autowired
    private UserFollowMapper userFollowMapper;

    /**
     * 发送消息（含业务校验+消息状态同步）
     */
    @Override
    @Transactional(rollbackFor = Exception.class) // 事务保证：消息和状态必须同时保存
    public boolean sendMessage(Integer receiverId, String content) {
        UserDTO currentUser = UserHolder.getUser();
        Integer senderId = currentUser.getId();

        // 1. 基础校验：不能给自己发消息
        if (senderId.equals(receiverId)) {
            return false;
        }

        // 2. 业务校验：未关注用户只能发1条未回复消息
        boolean isFollowed = userFollowMapper.isFollowed(senderId, receiverId);
        if (!isFollowed) {
            Integer unrepliedCount = userMessageMapper.countUnrepliedMessages(senderId, receiverId);
            if (unrepliedCount >= 1) {
                return false;
            }
        }

        // 3. 保存消息到user_message表（状态默认为0-未读）
        UserMessage message = new UserMessage();
        message.setSenderId(senderId);
        message.setReceiverId(receiverId);
        message.setContent(content);
        message.setCreateTime(LocalDateTime.now());
        message.setStatus(0); // 0-未读，1-已读，2-已回复
        userMessageMapper.insert(message);

        // 4. 同步保存消息状态到user_message_status表（默认为0-未读）
        UserMessageStatus status = new UserMessageStatus();
        status.setMessageId(message.getId()); // 关联消息ID
        status.setReceiverId(receiverId);     // 接收者ID
        status.setIsRead(0);                  // 0-未读，1-已读
        messageStatusMapper.insert(status);

        return true;
    }

    /**
     * 获取与指定用户的历史会话（分页）
     */
    @Override
    public List<UserMessageVO> getConversation(Integer receiverId, Integer page, Integer size) {
//        UserDTO currentUser = UserHolder.getUser();
//        if (currentUser == null) {
//            return null;
//        }
//        Integer currentUserId = currentUser.getId();
//        Integer offset = (page - 1) * size;
//        // 调用Mapper查询会话（包含发送者昵称、头像、已读状态）
//        return userMessageMapper.selectConversation(currentUserId, receiverId, size, offset);
        UserDTO currentUser = UserHolder.getUser();
        if (currentUser == null) {
            return null;
        }
        Integer currentUserId = currentUser.getId();
        Integer offset = (page - 1) * size;
        // 调用Mapper查询会话（包含发送者昵称、头像、已读状态）
        // 将currentUserId作为userId1，receiverId作为userId2
        return userMessageMapper.selectConversation(currentUserId, receiverId, size, offset);
    }

    /**
     * 批量标记消息为已读
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean markAsRead(List<Integer> messageIds) {
        if (messageIds == null || messageIds.isEmpty()) {
            return false;
        }
        UserDTO currentUser = UserHolder.getUser();
        if (currentUser == null) {
            return false;
        }
        Integer receiverId = currentUser.getId();
        // 1. 更新user_message_status表的is_read状态
        int updateCount = messageStatusMapper.batchMarkAsRead(receiverId, messageIds);
        // 2. 同步更新user_message表的status为1-已读
        userMessageMapper.batchUpdateStatus(messageIds, 1); // 需在Mapper中新增该方法
        return updateCount > 0;
    }
    /**
     * 获取当前用户的未读消息总数
     */
    @Override
    public Integer getUnreadCount() {
        UserDTO currentUser = UserHolder.getUser();
        if (currentUser == null) {
            return 0;
        }
        // 从user_message_status表查询接收者为当前用户且is_read=0的记录数
        return messageStatusMapper.countUnreadByReceiverId(currentUser.getId()); // 需在Mapper中新增该方法
    }
    /**
     * 实现：查询当前用户收到的消息
     */
    /**
     * 修正：确保方法签名与接口完全一致
     * 方法名、参数类型/顺序、返回值类型必须和UserMessageService接口中的定义一致
     */
    @Override // 必须添加@Override注解，强制检查是否正确覆盖
    public PageResult<UserMessageVO> getReceivedMessages(Integer page, Integer size, Integer status) {
        // 1. 登录校验
        UserDTO currentUser = UserHolder.getUser();
        if (currentUser == null) {
            return new PageResult<>(0L, page, size, null);
        }
        Integer receiverId = currentUser.getId();

        // 2. 分页参数处理
        if (page == null || page < 1) {
            page = 1;
        }
        if (size == null || size < 1 || size > 100) {
            size = 20;
        }
        Integer offset = (page - 1) * size;

        // 3. 查询数据
        List<UserMessageVO> messageList = userMessageMapper.selectReceivedMessages(
                receiverId, status, size, offset);
        Long total = userMessageMapper.countReceivedMessages(receiverId, status);

        // 4. 返回结果
        return new PageResult<>(total, page, size, messageList);
    }
}